#!/usr/bin/env python 
# -*- coding:utf-8 -*-
"""
Description: 自动监控集群信息，自动钉钉预警，自动恢复节点
"""

import time

import ruamel.yaml as yaml

from db.query import MySQLBase
from dingTalk.dingTalkMessage import mcne, jdjc
from dingTalk.sendDingTalk import DingTalkAPI
from logger import logger


class Recover:
    def __init__(self):
        self.mysql = MySQLBase()
        self.dta = DingTalkAPI()

    def check(self, data):
        """检测节点状态, 返回异常节点名称"""
        logger.info("检测节点状态")
        member_host = ''
        for row in data:
            member_state = row[4]
            if member_state == 'ERROR':
                member_host = row[2]
                member_mode = row[5]
                logger.warning("{} 节点异常".format(member_host))
                nowtime = time.strftime("%Y-%m-%d %H:%M:%S")
                msg = mcne.format(member_host, member_state, member_mode, nowtime)
                self.dta.dingtalk(msg)
                logger.info("钉钉发送成功")
                break
            logger.info("{} 节点正常".format(row[2]))
        return member_host

    def recover(self, member_host):
        """自动恢复集群，返回异常的节点信息"""
        ys = yaml.load(open('./conf/dbinfo.yaml', 'r').read(), Loader=yaml.Loader)
        for db in ys['DBDIC_INFO']['mysql']:
            if db['host'] == member_host:
                sql_str = """stop group_replication;"""
                res = self.mysql.query(db, sql_str)
                if res:
                    msg = "{} 停止复制组，失败".format(member_host)
                    logger.info(msg)
                    nowtime = time.strftime("%Y-%m-%d %H:%M:%S")
                    self.dta.dingtalk(jdjc.format(msg, nowtime))
                    logger.info("钉钉发送成功")
                    exit(1)
                else:
                    logger.info("{} 停止复制组，成功".format(member_host))
                    time.sleep(2)
                    sql_str = """start group_replication;"""
                    res = self.mysql.query(db, sql_str)
                    if res != 0:
                        logger.info("{} 启动复制组，成功".format(member_host))
                        return db
                    else:
                        msg = "{} 启动复制组，失败".format(member_host)
                        logger.info(msg)
                        nowtime = time.strftime("%Y-%m-%d %H:%M:%S")
                        self.dta.dingtalk(jdjc.format(msg, nowtime))
                        logger.info("钉钉发送成功")
                        exit(1)
